/* Copyright Andy Mitchell 2007. No warranties */

var GTDDEBUGMODE = true;
var GTDDEBUGMODE_DB = false;

function GTDInboxBrowser(){

try{
	var browser_appcontent = window.document.getElementById("appcontent");
	this.db = new GTDInboxDB("gtdinbox.sqlite");
	this.options = new FFOptions();
	this.checkOptions();
	this.install(false);
	
	this.stringBundle = document.getElementById("string-bundle");
	this._locale = this.stringBundle.getString("localename");

	if( this.options.getOption("char", "gtdinbox.debugMode")=="1" ){
		GTDDEBUGMODE = true;
	}else{
		GTDDEBUGMODE = false;
	}
		
	
	// Setup event handlers
	var fNewPage = this.createFNewPage();
	browser_appcontent.addEventListener("DOMContentLoaded", fNewPage, false);
	
	// Tab Events
	var tabContainer = gBrowser.tabContainer;
	var fTabClose = function(event){
			var currentBrowser = event.target.linkedBrowser;
			if( currentBrowser ){	// useful to block iframes
				var tabGTD = currentBrowser.gtdinboxPage;
				if( tabGTD ) tabGTD.unload();
			}
		};
	tabContainer.addEventListener("TabClose", GIPROTOTYPE.bind(this, fTabClose), false);

}catch(e){
	if( GTDDEBUGMODE ) alert("GTDInboxBrowser constructor\n" + e.toString());
}
}

GTDInboxBrowser.prototype.getLocalHtmFile = function(filename){
	return "chrome://gtdinbox/content/locale/" + this._locale + "/" + filename + ".htm";
};

GTDInboxBrowser.prototype.saveSettings = function(){
	var s = json.stringify( this.settings );
	this.options.setOption( "char", "gtdinbox.settings", s );
}
GTDInboxBrowser.prototype.createDefaultSettings = function(){
	var settings = {};	// defaults
	settings.labels = {};
	settings.labels.types = {};
	settings.labels.types["Statuses"] = {prefix: "S/", defaults: {NextAction:'Next Action', Action:'Action', WaitingOn:'Waiting On', SomeDay:'Some Day', Finished:'Finished'}};
	settings.labels.types["Projects"] = {prefix: "P/"};
	settings.labels.types["Contexts"] = {prefix: "C/"};
	settings.labels.types["References"] = {prefix: "R/"};
	settings.labels.types["Old"] = {name:"Old Items", prefix: "Old/"};
	settings.labels.types["Misc"] = {prefix: ""};
	/*
	settings.filters = {};
	settings.filters["Statuses"] = {inlineTypes:[], extendTypes:[]};
	settings.filters["Projects"] = {inlineTypes:["Statuses"], extendTypes:["Contexts", "References"]};
	settings.filters["Contexts"] = {inlineTypes:["Statuses"], extendTypes:[]};
	settings.filters["References"] = {inlineTypes:[], extendTypes:[]};
	settings.filters["Old"] = settings.filters["Projects"];
	settings.filters["Contacts"] = {inlineTypes:["Statuses"], extendTypes:["Projects", "References"]};
	settings.filters["Misc"] = {inlineTypes:[], extendTypes:[]};
	*/
	settings.labels.starForNextAction = true;
	settings.labels.onlyOneStatus = true;
	settings.async = {};
	settings.async.popupNewTab = false;
	return settings;
};
GTDInboxBrowser.prototype.checkOptions = function(){
	this.settings = json.parse( this.options.getOption("char", "gtdinbox.settings", "{}") );
	if( !this.settings ) this.settings = {};
	
	var settings = this.createDefaultSettings();
	GIPROTOTYPE.extend(this.settings, settings);
	this.saveSettings();
	
	/*
	// First call?
	if( !this.lastOptionId ){	// First call, just init it
		this.lastOptionId = this.options.getOption("char", "gtdinbox.lastOptionId");
		if( !this.lastOptionId ){	// set initial value
			this.lastOptionId = (new Date()).valueOf();
			this.options.setOption("char", "gtdinbox.lastOptionId", this.lastOptionId );
		}
		return;
	}
	
	// Reload?
	if( this.lastOptionId!=this.options.getOption("char", "gtdinbox.lastOptionId") ){	// reload		
		this.lastOptionId = this.options.getOption("char", "gtdinbox.lastOptionId");
	}
	*/
};

GTDInboxBrowser.prototype.createFNewPage = function(){
	var gtdinboxBrowser = this;
	var fNewPage = function(event){
			var currentBrowser = gBrowser.getBrowserForDocument(event.originalTarget);
			if( currentBrowser ){	// useful to block iframes
				try{
				var tabGTD = currentBrowser.gtdinboxPage;
				var loc = event.originalTarget.location;
				var newUrl = loc.href;
				var gtdinboxPage = null;
				if( tabGTD ){
					tabGTD.unload();
				}
				if( /^http(s?):\/\/mail.google.com/.test(newUrl) ){
					gtdinboxPage = new GTDInboxPage(gtdinboxBrowser, event.originalTarget);	// create new one:
					//gtdinboxBrowser.checkOptions();	// TODO DITCH THIS
				}
				}catch(e){if( GTDDEBUGMODE ) alert("fNewPage\n" + e.toString())}
			}
		};
	return fNewPage;
};




GTDInboxBrowser.prototype.getBrowserFromEvent = function(event){gBrowser.getBrowserForDocument(event.originalTarget);}; 




GTDInboxBrowser.prototype.install = function(reset){
try{
	var lastVersion = this.options.getOption("char", "gtdinbox.lastVersion", "");
	lastVersion = lastVersion? parseFloat(lastVersion):0;
	
	if( !reset && lastVersion==1.94 ) return;
	if( reset ) lastVersion = 0;
	
	
	if( lastVersion < 1.90 ){
	
		this.showMsg = "welcome";
		if( this.options.getOption("char", "Gtd.InstallOptionsComplete") ){	// install before
			this.showMsg = "update";
		}
		
		this.options.setOption("char", "gtdinbox.debugMode", "1");
	
		this.db.execute("DROP TABLE IF EXISTS project_label_activity");
		this.db.execute("CREATE TABLE project_label_activity (label VARCHAR(50) NOT NULL, thread VARCHAR(20) NOT NULL, contact VARCHAR(100) NOT NULL, date INTEGER)");
	
		this.createTable("auto_labelled", false, "label VARCHAR(255), msgid VARCHAR(25) NOT NULL", ["msgid, account"]);
		
		//this.createTable("threads", true, "thread VARCHAR(25)", null, ["thread"]);
		//this.createTable("labels", true, "label VARCHAR(255)", null, ["label"]);
		//this.createTable("contacts", true, "contact VARCHAR(150)", null, ["contact"]);
		//this.createTable("thread_labels", false, "thread_id INTEGER, label_id INTEGER", null, ["thread_id, label_id"]);
		//this.createTable("thread_contacts", false, "thread_id INTEGER, contact_id INTEGER, type INTEGER", null, ["thread_id, contact_id"]);	// type is 0: sender, 1: recipient
		this.createTable("thread_labels", false, "thread VARCHAR(25), label VARCHAR(255)", null, ["thread, label"]);
		this.createTable("thread_contacts", false, "thread VARCHAR(25), contact VARCHAR(150), type INTEGER", null, ["thread, contact"]);	// type is 0: sender, 1: recipient	
			
		lastVersion = 1.90;
	}
	if( lastVersion < 1.93 ){
		this.createTable("contact_emails", false, "contact_name VARCHAR(150), contact_email VARCHAR(150)", null, ["contact_name, contact_email"]);
			
		lastVersion = 1.93;
	}
	if( lastVersion < 1.94 ){
		this.settings.labels.starForNextAction = true;
		this.settings.labels.onlyOneStatus = true;
		this.settings.labels.types.Statuses.defaults.Finished = "Finished";
		this.saveSettings();
		
		if( !this.queuedOnLoad ) this.queuedOnLoad = [];	// functions to be executed next time a gtdinboxpage loads
		var f = function(){
			try{
				var fAddLabel = GIPROTOTYPE.bind(this, function(){
					if( !this._labels.hasLabel( this.gtdinboxBrowser.settings.labels.types.Statuses.prefix + "Finished" ) ){
						var finalCallback = GIPROTOTYPE.bind(this, function(){
							var el = this.gmailDOM.element("inbox-link");
							GIPROTOTYPE.doMouseEvent(this.doc, el, "click");	// refresh
						});
						this.gmailDOM.addLabel( this.gtdinboxBrowser.settings.labels.types.Statuses.prefix + "Finished", null, finalCallback);
					}
				});
				setTimeout(fAddLabel, 2000);
			}catch(e){
				if( GTDDEBUGMODE ) alert("install 1.94 queueonload\n" + e.toString());
			}
		};
		this.queuedOnLoad.push(f);	// executes in gtdinboxpage scope
		
		lastVersion = 1.94;
	}
		
	// Finally, record our update:
	this.options.setOption("char", "gtdinbox.lastVersion", lastVersion);
	
}catch(e){
	if( GTDDEBUGMODE ) alert("GtdinboxBrowser install\n" + e.toString());
}
};
GTDInboxBrowser.prototype.createTable = function(name, useId, fields, indices, uniqueIndices){
	if( useId ) fields = "id INTEGER PRIMARY KEY AUTOINCREMENT, " + fields;
	fields += ", account VARCHAR(100), date INTEGER, session INTEGER, session_modified INTEGER";	// session/date used for server syncing; when it comes (upload, make sure both sessions are set. if update, set session_modified to null; and issue 'update' command when sent to server). 
	
	this.db.execute("DROP TABLE IF EXISTS " + name);
	this.db.execute("CREATE TABLE " + name + " (" + fields + ")");
	var ic = 0;
	if( indices ){
		for( var i = 0; i < indices.length; i++ ){
			this.db.execute("CREATE INDEX " + name + "_idx" + ic++ + " ON " + name + "(" + indices[i] + ")");
		}
	}
	if( uniqueIndices ){
		for( var i = 0; i < uniqueIndices.length; i++ ){
			this.db.execute("CREATE UNIQUE INDEX " + name + "_idx" + ic++ + " ON " + name + "(" + uniqueIndices[i] + ")");
		}
	}
};
